var util = require('../../utils/util.js');
var app = getApp();
var base64 = require('../../utils/Base64');
const ttParse = require('../../ttParse/ttParse.js');

Page({
  data: {
    util: util,
    orgInfo: '',
    org_name: '',
    bottom_nav_data: [],
    isIphone_x: false,
  
    screen_w: 320,
    screen_h: 480,

    userList: [],

    noMessage: false,

    showVideo: false,
    dongtaiDatas: [],

    newRigistUser: '',

    messagehtml: '',

    isShowMessage: true
  },

  cuid: '',
  token: '',

  runOnLoad: false,

  isFromShare: false,
  isFromSubMsg: false,
  fromSubUid: '',

  lat: '',
  lon: '',

  onLoad: function (data) {
    console.log("onLoad params:", data)
    
    this.runOnLoad = true
    
    //点击分享进来的
    this.isFromShare = (data.share && data.share == 'true') ? true : false
    //点击订阅消息进来的
    this.isFromSubMsg = (data.fmsg && data.fmsg == 'true') ? true : false
    if (this.isFromShare) {
      this.fromSubUid = data.uid
    } else if (this.isFromSubMsg) {
      this.fromSubUid = data.fuid
    }
    
    if(this.isFromSubMsg) {
      //已经使用了一次订阅消息，清除缓存
      app.removeSubscribeMessageCache()
    }

    var that = this
    that.initIndexView(data)
    app.getWxCheck(function(show) {
      that.setData({
        showVideo: show
      })
      if(show) {
        that.getLoginUserInfo(false)
        that.startTimer()
      } else {
        that.getGoodsListData()
      }
    }, true)

    app.getLocation(function(res) {
      if (res.latitude && res.longitude) {
        that.lat = res.latitude
        that.lon = res.longitude
      }
      that.getNearestDatas()
    })

    this.loadDefaultShareImage()
  },

  getLoginUserInfo: function (reAuth) {
    var that = this;
    //读取登录用户信息
    app.LoginUserInfo(function (res) {
      console.log("登录用户信息：", res);
      if (res && res != '-1') {
        that.cuid = res.uid
        that.token = res.token
        that.setData({
          userInfo: res,
          hasMsgCount: parseInt(res.scorecoin) - parseInt(res.scorenum)
        });
        that.getChartList(that.cuid)

        if(that.isFromSubMsg && that.fromSubUid.length > 0) {
          tt.navigateTo({
            url: '/pages/chatMessage/chatMessage?uid=' + that.fromSubUid,
          })
          that.isFromSubMsg = false
          that.fromSubUid = ''
        } else if (that.isFromShare && that.fromSubUid.length > 0) {
          tt.navigateTo({
            url: '/pages/userDetail/userDetail?uid=' + that.fromSubUid,
          })
        }
      }
    }, reAuth);
  },

  initIndexView: function (data) {
    var that = this;
    //初始化底部导航
    app.getBottomNavData('index/index', function (nav_data) {
      that.setData({
        bottom_nav_data: nav_data,
        nav_bgColor: nav_data[0].bgcolor
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  requestTimer: '',
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this
    app.initScreenInfo(function(res){
      if(res) {
        that.setData({
          isIphone_x: app.isIphone_x,
          screen_w: app.screen_w,
          screen_h: app.screen_h
        });
      }
    })

    if (!that.runOnLoad && that.cuid.length > 0) {
      that.getChartList(that.cuid)
    }
    if(!that.runOnLoad){
      this.startTimer()
    }
    that.runOnLoad = false
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("onHide!!!!!! 清除定时器")
    this.clearTimer()
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("onUnload!!!!!! ")
    this.clearTimer()
  },

  /**开启定时器 */
  startTimer() {
    if(!this.data.showVideo) return
    this.clearTimer()
    var that = this
    console.log("开启定时器")
    that.requestTimer = setInterval (
      function () {
        that.getChartList(that.cuid)
        that.getNewRegisterUser()
      }
    , 15000)
  },

  /**清除定时器 */
  clearTimer() {
    if (this.requestTimer) {
      console.log("清除定时器")
      clearInterval(this.requestTimer)
    }
    this.requestTimer = ''
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    tt.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  goAtherPage: function (e) {
    console.log("goAtherPage!!!!!!!!");
    var url = e.currentTarget.dataset.link;
    tt.navigateTo({
      url: url
    })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    tt.redirectTo({
      url: url
    })
  },

  //底部导航跳转
  navigtionClick: function (e) {
    console.log("点击参数：", e);
    var path = e.currentTarget.dataset.path;
    console.log("跳转连接信息：", path);
    if (path) {
      if (path.indexOf('navto:') == 0) {
        var navPath = path.slice(6);
        tt.navigateTo({
          url: navPath,
        })
      } else {
        tt.redirectTo({
          url: path
        });
      }
    }
  },

   //获取联系人列表
  getChartList: function() {
    var that = this
    util.api_go({
        data: {
          "publickey": util.publiccode,
          "ac": "getmsglist",
          "uid": that.cuid,
          "page": 1,
          "num": 100
        },
        success: function (responseData) {
          console.log("联系人列表：", responseData);
          if(responseData.data){
            if(responseData.data.length > 0) {
              responseData.data.forEach(function(m) {
                if (m.touid == that.cuid) {//对方发给我的信息
                  m.newMsgCount = parseInt(m.not_read_touid)
                  m.ta_uid = m.uid
                  m.ta_uname = m.user.uname
                  m.ta_avatar = m.user.avatar
                } else {//我发给对方的消息
                  m.newMsgCount = parseInt(m.not_read_uid)
                  m.ta_uid = m.touid
                  m.ta_uname = m.touser.uname
                  m.ta_avatar = m.touser.avatar
                }
                let charsToReplace = ["-", ":", " "]
                let timeInt = parseInt(m.last_time.replace(new RegExp(charsToReplace.join("|"), "g"), ""))
                m.timeInt = timeInt
                let len = m.last_time.length
                m.lastTime = m.last_time.slice(2, len - 3)
                m.lastMsg = base64.decode(m.last_msg)
              })
              let msgUserList = responseData.data.sort((a, b) => b.timeInt - a.timeInt)
              that.setData({
                isShowMessage: true,
                noMessage: false,
                userList: msgUserList
              })
            } else {
              that.setData({
                isShowMessage: false,
                noMessage: true
              })
            }
          } else {
            tt.showToast({
              title: '获取联系人失败',
            })
          }
        }
      });
  },

  // http://admin.jawanology.com/go.php?ac=getNearestGonggao&lon=1&lat=1&publickey=ZGZvI1mi8Q
// 昨天说的那个接口，传入lon和lat，返回距离最近的公告
getNearestDatas: function () {
  var that = this
  var params = {
    publickey: util.publiccode,
    ac: "getNearestGonggao",
    lat: that.lat,
    lon: that.lon
  };
  console.log("获取最近的推广数据：", params)
  util.api_go({
    data: params,
    success: function (responseData) {
      console.log("最近的推广数据：", responseData)
      if (!responseData.data.msg) {
        //处理message  
        var detailMessage = responseData.data.message
        console.log("detailMessage: ", detailMessage)
        ttParse.ttParse('messagehtml', 'html', detailMessage, that, 5)
      } else {
        that.setData({
          isShowMessage: true
        })
      }
      
    }
  })
},

changeView:function () {
  var showMsg = !this.data.isShowMessage
  this.setData({
    isShowMessage: showMsg
  })
},


  //以下是审核内容
  getGoodsListData:function(){
    var that = this;
    this.setData({
      hasLoadding: true
    });
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '8',
      postuid: util.orgid,
      page: 1,
      num: 30
    };
    console.log("动态请求参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        console.log("动态数据：", responseData);
        that.setData({
          dongtaiDatas: responseData.data
        })
        tt.hideLoading();
      }
    });
  },



  getNewRegisterUser: function () {
    let curTime = (new Date().getTime()) / 1000
    if (curTime - app.globalData.lastGetRegisterUserTime < 60 || !this.data.showVideo) {
      console.log("1分钟请求一次")
      return
    }
    app.globalData.lastGetRegisterUserTime = curTime
    var that = this
    let commitData = {
      publickey: util.publiccode,
      "ac": "getRecentReg"
    };
    console.log("获取新注册用户：", commitData)
    util.api_go({
      data: commitData,
      success: function(responseData) {
        console.log("获取新注册用户返回：", responseData);
        if (responseData.data && !responseData.data.msg) {
          if (app.globalData.newRegisterUid != responseData.data.uid) {
            app.globalData.newRegisterUid = responseData.data.uid
            that.setData({
              newRigistUser: responseData.data
            })
            setTimeout(function() {
              that.setData({
                newRigistUser: ''
              })
            },6000)
          } else {
            console.log("同一个新注册用户：");
          }
        }
      }
    });
  },


  //index 001  获取默认分享图片
  loadDefaultShareImage: function (index) {
    var params = {
      "publickey": util.publiccode,
      "ac": "indexslide",
      "uid": util.orgid,
      "block": '1'
    };
    util.api({
      data: params,
      success: function (responseData) {
        console.log("DefaultShareImage info:", responseData);
        var result = responseData.data;
        if (result && result.length > 0) {
          util.defaultShareImgUrl =result[0].photo
          console.log("defaultShareImgUrl:" + util.defaultShareImgUrl);

        }
      }
    });
  },


  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var shareTitle = "我在这里认识很多单身朋友，总有你中意的！"
    var shareImgUrl = that.getShareImgUrl()
    var sharePath = '/pages/launch/launch?share=true&uid=' + that.cuid
    if (!shareImgUrl || shareImgUrl.length <= 0) {
      if(that.data.showVideo) {
        shareImgUrl = util.defaultShareImgUrl
      }
      sharePath = '/pages/launch/launch?goliaota=true'
    }
    if (!that.data.showVideo) {
      shareTitle = "朋友，我发现一些美食和好住处"
      sharePath = '/pages/index/index'
    }
    return {
      title: shareTitle,
      imageUrl: shareImgUrl,
      path: sharePath
    };
  },

  getShareImgUrl() {
    if (this.data.userInfo && this.data.userInfo.photo && this.data.userInfo.photo.indexOf('http') == 0) {
      return this.data.userInfo.photo
    }
    return ''
  }

})